﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Cache;
using System.Web;

namespace AG_Apps_Cloud_Services_WCF_Web_Role.Handlers
{
    /// <summary>
    /// Summary description for GetImage
    /// </summary>
    public class GetImage : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            try
            {
                HttpRequest request = context.Request;
                HttpResponse response = context.Response;
                WebResponse responseHTTP = null;
                string imageURL = null;

                imageURL = Convert.ToString(request.QueryString["ImageUrl"]);

                if (!string.IsNullOrEmpty(imageURL))
                {
                    WebRequest requestHTTP = WebRequest.Create(imageURL);
                    requestHTTP.Method = "GET";
                    requestHTTP.UseDefaultCredentials = true;
                    requestHTTP.CachePolicy = new RequestCachePolicy(System.Net.Cache.RequestCacheLevel.CacheIfAvailable);

                    responseHTTP = requestHTTP.GetResponse();

                    Stream httpStream = responseHTTP.GetResponseStream();
                    byte[] buffer = new byte[1024];
                    int len = (int)responseHTTP.ContentLength;
                    int bytes;

                    while (len > 0 && (bytes = httpStream.Read(buffer, 0, buffer.Length)) > 0)
                    {

                        context.Response.OutputStream.Write(buffer, 0, bytes);
                        len -= bytes;
                    }
                    response.ContentType = responseHTTP.ContentType;
                    response.Flush();
                }
            }
            catch (Exception ex)
            {
                context.Response.ContentType = "text/plain";
                context.Response.Write(ex.Message);
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}